#!/bin/bash
set -euo pipefail

#======== 颜色 ==========
R='\e[31m'; G='\e[32m'; Y='\e[33m'; B='\e[36m'; N='\e[0m'

#======== 必须是 root ==========
if [[ $EUID -ne 0 ]]; then
    echo -e "${R}请以 sudo 运行：${N}sudo bash $0"
    exit 1
fi

#======== 找分区 ==========
mapfile -t opts < <(
    lsblk -rno NAME,FSTYPE,LABEL,UUID,SIZE |
    awk '$2!~/^(swap|)$/ && $1~/[^0-9]$/ {print "/dev/"$1,$2,$3,$4,$5}'
)

if ((${#opts[@]}==0)); then
    echo -e "${R}没找到可挂载的分区${N}"; exit 1
fi

#======== 选择菜单 ==========
echo -e "${B}请选择要开机自动挂载的分区：${N}"
for i in "${!opts[@]}"; do
    IFS=' ' read -r dev fst label uuid size <<<"${opts[i]}"
    printf "%2s) %-10s %-8s %-20s %s\n" "$((i+1))" "${dev##*/}" "$fst" "${label:-无标签}" "$size"
done
echo -n "序号 (1-${#opts[@]}): "; read -r idx
((idx>0 && idx<=${#opts[@]})) || { echo -e "${R}无效序号${N}"; exit 1; }

IFS=' ' read -r DEV FSTYPE LABEL UUID SIZE <<<"${opts[idx-1]}"
LABELSAFE=${LABEL:-disk${idx}}
MNT="/run/media/deck/${LABELSAFE// /_}"   # 空格转下划线

#======== 确认/修改挂载点 ==========
echo -e "\n${B}分区信息：${N}"
echo "设备： $DEV"
echo "文件系统： $FSTYPE"
echo "UUID： $UUID"
echo "容量： $SIZE"
echo -e "${Y}默认挂载点：$MNT${N}"
echo -n "回车确认，或输入新路径： "; read -r newmnt
[[ -n $newmnt ]] && MNT=$newmnt

#======== 创建挂载点 ==========
mkdir -p "$MNT"

#======== 构造 fstab 选项 ==========
case "$FSTYPE" in
    ntfs)  OPTS="defaults,nofail,uid=1000,gid=1000" ;;
    exfat) OPTS="defaults,nofail,uid=1000,gid=1000" ;;
    *)     OPTS="defaults,nofail" ;;
esac
NEWLINE="UUID=$UUID $MNT $FSTYPE $OPTS 0 0"

#======== 写前备份 ==========
cp /etc/fstab /etc/fstab.bak.$(date +%s)

#======== 添加并验证 ==========
echo -e "\n${B}写入 fstab：${N}"
echo "$NEWLINE" | tee -a /etc/fstab
echo -e "${Y}正在 mount -a 测试 …${N}"
if systemctl daemon-reload && mount -a; then
    echo -e "${G}✅ 挂载成功！重启后会自动挂载到 $MNT${N}"
else
    echo -e "${R}❌ 测试挂载失败，正在回滚 …${N}"
    mv /etc/fstab.bak.* /etc/fstab
    exit 1
fi

#======== 可选：DeckGuard 备份 ==========
if [[ -d /etc/deck-guard/fstab ]]; then
    cp /etc/fstab /etc/deck-guard/fstab/
    echo -e "${B}已同步到 DeckGuard 备份目录${N}"
fi